package filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter({"/home","/home.jsp"})
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("MyFilter初始化了");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("MyFilter执行过滤逻辑");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        if (username == null){
            request.setAttribute("msg","请先登录！");
            request.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
        }
        System.out.println("MyFilter before doFilter");

        filterChain.doFilter(servletRequest, servletResponse);//放行

        System.out.println("MyFilter after doFilter");

    }

    @Override
    public void destroy() {
        System.out.println("MyFilter销毁了");
    }
}